import 'package:e_reception_flutter/net/net_api.dart';
import 'package:e_reception_flutter/net/server_api.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/app_main.dart';
import 'package:e_reception_flutter/ui/check_in_record/check_in_record_browser/pages/bean/check_in_record_brower_for_type_response_bean.dart';
import 'package:e_reception_flutter/ui/company/company_add_user_edit_info/bean/company_add_user_edit_info_type.dart';
import 'package:e_reception_flutter/ui/company/company_add_user_update_info/bean/face_user_info_response_bean.dart';
import 'package:e_reception_flutter/ui/company/company_detail/event/refresh_company_detail_page_event.dart';
import 'package:e_reception_flutter/ui/create_user/edit_user/bean/edit_user_info_response_bean.dart';
import 'package:e_reception_flutter/ui/create_user/edit_user/bean/edit_user_upload_bean.dart';
import 'package:e_reception_flutter/ui/create_user/user_selectsort/update_task_view_model.dart';
import 'package:e_reception_flutter/ui/person_detail/bean/person_detail_response_bean.dart';
import 'package:e_reception_flutter/ui/person_detail/person_detail_page.dart';
import 'package:e_reception_flutter/ui/person_detail/widgets/person_artificial_attendance_view_model.dart';
import 'package:e_reception_flutter/utils/app_monitoring_class.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/utils/vg_http_utils.dart';
import 'package:e_reception_flutter/utils/vg_hud_utils.dart';
import 'package:e_reception_flutter/utils/vg_matisse_utils.dart';
import 'package:e_reception_flutter/utils/vg_string_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/utils/vg_tool_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:vg_base/src/arch/base_state.dart';
import 'package:vg_base/vg_base_callback.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_http_lib.dart';
import 'package:vg_base/vg_pull_to_refresh_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';

class PersonDetailViewModel extends BasePagerViewModel<PersonDetailListItemBean,
    PersonDetailResponseBean> {

  ///App用户详情
  static const String USER_INFO_API =ServerApi.BASE_URL + "app/appFaceUserInfo";

  ///用户重复
  static final String _USER_REPEAT = "700";

  final String fuid;

  VoidCallback onPushNameRepeat;

  // ValueNotifier<FaceUserInfoBean> infoValueNotifier;
  ValueNotifier<PersonDetailResponseBean> infoValueNotifier;
  final PersonDetailPageState state;
  ValueNotifier<EditUserInfoDataBean> userInfoValueNotifier;
  PersonDetailViewModel(this.state, this.fuid)
      : super(state) {
    if (state!=null&&state is PersonDetailPageState) {
      onPushNameRepeat = state.pushNameRepeatDialog;
    }
    infoValueNotifier = ValueNotifier(null);
    userInfoValueNotifier = ValueNotifier(null);
  }

  ///编辑后保存用户请求
  void updateUserJurisdictionHttp(BuildContext context, EditUserUploadBean uploadBean,bool whetherReturn) async {
    if (uploadBean == null) {
      VgToastUtils.toast(context, "上传信息获取失败");
      return;
    }
    if (StringUtils.isNotEmpty(uploadBean?.phone) &&
        !VgToolUtils.isPhone(uploadBean?.phone)) {
      VgToastUtils.toast(context, "手机号不正确");
      return;
    }
    VgHudUtils.show(context, "保存中");
    if (StringUtils.isNotEmpty(uploadBean.headFaceUrl) &&
        !VgStringUtils.isNetUrl(uploadBean.headFaceUrl)) {
      try {
        String netFace = await VgMatisseUploadUtils.uploadSingleImageForFuture(
            uploadBean.headFaceUrl, isFace: true);
        if (StringUtils.isNotEmpty(netFace)) {
          uploadBean.headFaceUrl = netFace;
        } else {
          VgHudUtils.hide(context);
          VgToastUtils.toast(context, "上传头像失败");
          return;
        }
      } catch (e) {
        VgHudUtils.hide(context);

        VgToastUtils.toast(context, "上传头像失败");
        return;
      }
    }
    if (uploadBean.identityType == CompanyAddUserEditInfoIdentityType.superAdmin) {
      //超管时清空终端 部门 班级 （不用上传）
      uploadBean.departmentList = null;
      uploadBean.classIdList = null;
      uploadBean.terminalList = null;
    }

    var params = {
      "authId": UserRepository.getInstance().authId ?? "",
      "groupid": uploadBean?.groupBean?.groupid ?? "",
      "hsn": uploadBean.getHsnSplitStr() ?? "",
      "name": uploadBean?.name?.trim() ?? "",
      "roleid": uploadBean?.getIdentityIdStr() ?? "",
      "city": uploadBean?.cityId ?? "",
      //班级id
      "classids": uploadBean?.classIds() ?? "",
      "companyid":
      UserRepository.getInstance().userData?.companyInfo?.companyid ?? "",
      "courseids": "",
      "createuid": uploadBean?.createuid,
      "departmentid": uploadBean?.departmentId ?? "",
      "fuid": uploadBean?.fuid,
      "fid": uploadBean?.fid,
      "napicurl": uploadBean?.headFaceUrl ?? "",
      "nick": uploadBean?.nick ?? "",
      "number": uploadBean?.userNumber ?? "",
      "phone": globalSubPhone(uploadBean?.phone) ?? "",
      "projectid": uploadBean?.projectId ?? "",
      if (uploadBean.isNewPic())
        "putpicurl": uploadBean?.headFaceUrl ?? "",
      "punchDayCnt": 0,
      // "type": "", //用户状态00标记录入 01app手动添加
      if (StringUtils.isNotEmpty(uploadBean?.userid))
        "userid": uploadBean?.userid
    };
    StringBuffer departmentManageIds = StringBuffer();
    if (uploadBean.departmentList != null) {
      departmentManageIds.write(uploadBean.departmentList.join(','));
    }
    StringBuffer classIds = StringBuffer();
    if (uploadBean.classIdList != null) {
      classIds..write(uploadBean.classIdList.join(','));
    }
    if ((uploadBean.departmentList ?? []).isNotEmpty) {
      params["mDepartmentIds"] = departmentManageIds.toString();
    }
    if ((uploadBean.classIdList ?? []).isNotEmpty) {
      params["mClassIds"] = classIds.toString();
    }

    VgHttpUtils.post(ServerApi.BASE_URL + "app/appEditUser",
        params: params,
        callback: BaseCallback(onSuccess: (val) {
          VgHudUtils.hide(context);
          BaseResponseBean bean = BaseResponseBean.fromMap(val);
          if (bean.code == _USER_REPEAT) {
            if (onPushNameRepeat != null) {
              onPushNameRepeat.call();
            } else {
              throw UnimplementedError();
            }
            return;
          }
          VgToastUtils.toast(context, "更新成功");
          VgEventBus.global.send(RefreshPersonDetailEvent());
          VgEventBus.global.send(CompanyNumBarEventMonitor(delete: false));
          if(uploadBean?.headFaceUrl!="" && uploadBean?.headFaceUrl!=null){
            VgEventBus.global.send(new ArtificialAttendanceUpdateEvent(headFaceUrl: uploadBean?.headFaceUrl,fuid: uploadBean?.fuid));
          }
          // else{
          //   VgEventBus.global.send(RefreshCompanyDetailPageEvent(msg:'编辑员工'));
          // }
          if(whetherReturn) RouterUtils.pop(context, result: true);
          //是否是当前用户
          if (uploadBean.userid ==
              UserRepository.getInstance().userData?.user?.userid) {
            //自动更新数据
            UserRepository.getInstance()
                .loginService(isBackIndexPage: false)
                .autoLogin();
          }
          if(uploadBean?.isSuperAdminRole() ?? false ){
            getUserInfoHttp(uploadBean?.fuid);
          }
        }, onError: (msg) {
          VgHudUtils.hide(context);
          VgToastUtils.toast(context, msg);
        }));
  }


  ///获取用户信息请求
  void getUserInfoHttp(String fuid) {
    VgHttpUtils.get(USER_INFO_API,
        params: {
          "authId": UserRepository.getInstance().authId ?? "",
          "fuid": fuid ?? "",
        },
        callback: BaseCallback(onSuccess: (val) {
          EditUserInfoResponseBean bean = EditUserInfoResponseBean.fromMap(val);
          userInfoValueNotifier.value = bean?.data;
        }, onError: (msg) {
          VgToastUtils.toast(AppMain.context, msg);
        }));
  }

  ///设置特别关心
  void changeVeryCareStatus(
    BuildContext context,
    String fuid,
    String  isSpecial,
  ) {
    if (StringUtils.isEmpty(fuid)) {
      VgToastUtils.toast(context, "个人信息获取失败");
      return;
    }
    VgHttpUtils.post(NetApi.SPECIAL_FOCUS_FACE_USER_API,
        params: {
          "authId": UserRepository.getInstance().authId ?? "",
          //00取消 01关注
          "flg": isSpecial,
          "fuid": fuid ?? "",
        },
        callback: BaseCallback(onSuccess: (val) {
          VgEventBus.global.send(RefreshCompanyDetailPageEvent());
          // getRequestMethod();
          ///回调处理特别关心回调（接口保存判断，回调方法去除）
          // if(state!=null){
          //   state?.widget?.onChangeVeryCare?.call();
          // }
        }, onError: (msg) {
          VgToastUtils.toast(AppMain.context, msg);
        }));
  }

  @override
  void onDisposed() {
    infoValueNotifier?.dispose();
    userInfoValueNotifier?.dispose();
    super.onDisposed();
  }

  @override
  Map<String, dynamic> getQuery(int page) {
    Map<String, dynamic> map = {
      "authId": UserRepository.getInstance().authId ?? "",
      "current": page ?? 1,
      "size": 20,
      "fuid": fuid ?? "",
    };
    return map;
  }

  @override
  String getRequestMethod() {
    return HttpUtils.POST;
  }

  @override
  String getUrl() {
    return ServerApi.BASE_URL + "app/appTodayGroupPersonDetails";
  }

  @override
  PersonDetailResponseBean parseData(VgHttpResponse resp) {
    PersonDetailResponseBean vo = PersonDetailResponseBean.fromMap(resp?.data);
    loading(false);
    if(vo?.isSucceed()??false){
      infoValueNotifier?.value = vo;
    }else if(StringUtils.isNotEmpty(vo?.msg??"")){
      toast(vo?.msg??"");
      if("该用户已被删除" == (vo?.msg??"")){
        RouterUtils.pop(state.context);
      }
    }
    // infoValueNotifier?.value = vo?.data?.faceUserInfo;

    return vo;
  }

  @override
  String getBodyData(int page) {
    return null;
  }
}